<template>
  <div class="app-container">
    <!-- 车辆调度查询 -->
    <el-card shadow="never">
      <!-- <div class="flex gap-6 mb-6">
        <div class="flex-1 p-4 border rounded-lg bg-blue-50">
          <div class="text-sm text-gray-500 mb-2">今日配送任务</div>
          <div class="text-2xl font-medium">{{ deliveryStatusCount.totalCount }}</div>
        </div>
        <div class="flex-1 p-4 border rounded-lg bg-green-50">
          <div class="text-sm text-gray-500 mb-2">在途车辆</div>
          <div class="text-2xl font-medium">{{ deliveryStatusCount.deliveringCount }}</div>
        </div>
        <div class="flex-1 p-4 border rounded-lg bg-orange-50">
          <div class="text-sm text-gray-500 mb-2">待分配车辆</div>
          <div class="text-2xl font-medium">{{ deliveryStatusCount.pendingCount }}</div>
        </div>
        <div class="flex-1 p-4 border rounded-lg bg-purple-50">
          <div class="text-sm text-gray-500 mb-2">完成配送</div>
          <div class="text-2xl font-medium">{{ deliveryStatusCount.completedCount }}</div>
        </div>
      </div> -->
      <div class="mb-6">
        <el-form :inline="true">
          <el-form-item label="车牌号">
            <el-select
              v-model="filters.licensePlate"
              placeholder="请选择车牌号"
              class="!w-[192px]"
              clearable
              @change="handleSearch"
            >
              <el-option
                v-for="item in plateList"
                :key="item.licensePlate"
                :label="item.licensePlate"
                :value="item.licensePlate"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="司机姓名">
            <el-input
              v-noSpace
              v-model="filters.driverName"
              placeholder="司机姓名"
              class="!w-[192px]"
              clearable
              :prefix-icon="User"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="配送状态">
            <el-select
              v-model="filters.deliveryStatus"
              placeholder="配送状态"
              class="!w-[192px]"
              clearable
              :prefix-icon="Van"
              @change="handleSearch"
            >
              <el-option
                v-for="item in deliveryStatusList"
                :key="item.codeValue"
                :label="item.codeName"
                :value="item.codeValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="!rounded-button whitespace-nowrap"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button class="!rounded-button whitespace-nowrap" @click="handleReset">
              重置
            </el-button>
            <el-button
              class="!rounded-button whitespace-nowrap"
              @click="externalVehicleDialog.visible = true"
              v-hasPerm="'sys:vehicleScheduling:edit'"
            >
              新增车辆
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-loading="loading" :data="tableData">
        <el-table-column prop="licensePlate" label="车牌号" align="center" />
        <el-table-column prop="driverName" label="司机" align="center" />
        <el-table-column prop="contactInfo" label="联系方式" align="center" />
        <el-table-column prop="currentTask" label="当前任务" align="center">
          <template #default="scope">
            {{ scope.row.vehicleInfoDTOList[0]?.shipOrderCode || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="配送状态" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.vehicleStatus === 0" type="success">空闲</el-tag>
            <el-tag v-else-if="row.vehicleStatus === 1" type="warning">配送中</el-tag>
            <el-tag v-else-if="row.vehicleStatus === 2" type="danger">维修中</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isExternalVehicle" label="是否外部车辆" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.isExternalVehicle === 1" type="warning">是</el-tag>
            <el-tag v-else type="success">否</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="预计完成时间" align="center">
          <template #default="{ row }">
            {{ row.estimatedLoadingCompletionTime || "-" }}
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleViewDetail(scope.row)">
              查看详情
            </el-button>
            <el-button link type="warning" size="small" @click.stop="handleEdit(scope.row, 'edit')">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click.stop="handleDel(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="filters.pageNum"
        v-model:limit="filters.pageSize"
        @pagination="handleSearch"
      />
      <!-- 详情弹窗 -->
      <el-dialog v-model="detailDialogVisible" title="车辆详情" width="1000px" class="!rounded-lg">
        <div class="flex gap-6">
          <!-- 左侧任务列表 -->
          <el-scrollbar max-height="100%">
            <div class="w-[400px] border-r pr-6">
              <h3 class="text-lg font-medium mb-4">任务列表</h3>
              <div class="space-y-4">
                <div
                  v-for="task in selectedRow?.vehicleInfoDTOList"
                  :key="task.shipOrderCode"
                  class="p-4 border rounded-lg hover:bg-gray-50 cursor-pointer"
                >
                  <div class="flex justify-between items-center mb-2">
                    <el-text class="font-medium">
                      送货单号
                      <el-text type="primary">#{{ task.shipOrderCode }}</el-text>
                    </el-text>

                    <el-tag v-if="task.status === 4" type="danger" class="!rounded-button">
                      分拣中
                    </el-tag>
                    <el-tag v-if="task.status === 7" type="warning" class="!rounded-button">
                      装车中
                    </el-tag>
                    <el-tag v-if="task.status === 8" type="warning" class="!rounded-button">
                      配送中
                    </el-tag>
                    <el-tag v-if="task.status === 9" type="warning" class="!rounded-button">
                      配送完成
                    </el-tag>
                  </div>
                  <div class="text-gray-500 text-sm space-y-1">
                    <div>
                      <el-text class="font-medium">
                        销售单号
                        <el-text>#{{ task.saleCode }}</el-text>
                      </el-text>
                    </div>

                    <div>配送地址：{{ task.address }}</div>
                    <div>送货时间：{{ task.shipDate }}</div>
                    <div>
                      联系人：{{ (task.contactPerson || "") + " " + (task.contactPhone || "") }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-scrollbar>
          <!-- 右侧实时监控 -->
          <div class="flex-1 flex flex-col">
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-medium">实时监控</h3>
              <div class="flex items-center gap-2 text-sm">
                <div class="flex items-center">
                  <div
                    class="w-2 h-2 rounded-full bg-green-500 mr-1"
                    :class="{ 'bg-red-500': selectedRow?.vehicleStatus == 2 }"
                  />
                  <el-text>
                    {{
                      selectedRow?.vehicleStatus == 0
                        ? "空闲"
                        : selectedRow?.vehicleStatus == 1
                          ? "正常运行"
                          : "维修中"
                    }}
                  </el-text>
                </div>
                <div class="text-gray-400">|</div>
                <div>车速：{{ vehicleInfo.speed || 0 }}km/h</div>
                <div class="text-gray-400">|</div>
                <div>温度：{{ vehicleInfo.temperature || 0 }}°C</div>
              </div>
            </div>
            <div class="flex items-center gap-2 text-sm">
              <div class="text-gray-400">|</div>
              <div>目标位置： {{ selectedRow?.targetName }}</div>
              <div class="text-gray-400">|</div>
            </div>
            <div class="flex-1">
              <!-- 地图容器 -->
              <div
                v-if="selectedRow?.vehicleStatus == 0"
                class="w-full h-full min-h-xl flex items-center justify-center bg-gray-100"
              >
                <el-text>车辆无任务</el-text>
              </div>
              <div v-else>
                <Map
                  v-if="detailDialogVisible && selectedRow?.vehicleStatus !== 0"
                  :driver="selectedRow"
                  @getDriverInfo="handleGetDriverInfo"
                />
              </div>
            </div>
          </div>
        </div>
      </el-dialog>
    </el-card>
    <el-dialog
      v-model="externalVehicleDialog.visible"
      title="新增车辆"
      width="600px"
      class="!rounded-lg"
      @close="handleCarCloseDialog"
    >
      <div class="grid grid-cols-1 gap-4">
        <el-form
          ref="externalVehicleRef"
          :model="newVehicle"
          :rules="externalVehicleRules"
          label-width="100px"
        >
          <el-form-item prop="licensePlate" label="车牌号">
            <el-input v-noSpace v-model="newVehicle.licensePlate" placeholder="请输入车牌号" />
          </el-form-item>

          <el-form-item prop="driverName" label="司机姓名">
            <el-input v-noSpace v-model="newVehicle.driverName" placeholder="请输入司机姓名" />
          </el-form-item>
          <el-form-item prop="contactInfo" label="联系电话">
            <el-input v-noSpace v-model="newVehicle.contactInfo" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item prop="remark" label="备注信息">
            <el-input
              v-noSpace
              v-model="newVehicle.remark"
              type="textarea"
              :rows="3"
              maxlength="500"
              show-word-limit
              placeholder="请输入备注信息"
            />
          </el-form-item>

          <el-form-item prop="isExternalVehicle" label="是否外部车辆">
            <el-switch
              v-model="newVehicle.isExternalVehicle"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-text class="dialog-footer">
          <el-button @click="externalVehicleDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleAddCar">确定</el-button>
        </el-text>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { User, Van } from "@element-plus/icons-vue";
import vehicleSchedulingApi, {
  ExternalVehicle,
  VehicleMonitoringCount,
  vehicleScheduling,
  vehicleSchedulingQuery,
} from "@/api/LogisticsManagement/vehicleScheduling";
import vehicleMonitoringDataApi, {
  VehicleMonitoringData,
} from "@/api/LogisticsManagement/vehicleMonitoringData";

const detailDialogVisible = ref(false);
const selectedRow = ref<vehicleScheduling & { targetName: string }>();
const externalVehicleDialog = ref({
  visible: false,
  title: "新增车辆",
});

//打开新增车辆弹窗

const loading = ref(false); // 控制加载状态

const newVehicle = ref<ExternalVehicle>({
  licensePlate: "",
  isExternalVehicle: 0,
  driverName: "",
  contactInfo: "",
  remark: "",
});

//车牌数据
const plateList = ref();
//获取所有车
const getPlateList = () => {
  vehicleMonitoringDataApi.getVehicleMonitoring({ pageNum: 1, pageSize: 999 }).then((res: any) => {
    plateList.value = res.list;
  });
};

//配送状态
const deliveryStatusList = ref([
  //0=待确认 1=待配送 2=配送中 3=配送完成'
  // { codeValue: "0", codeName: "待确认" },
  { codeValue: 0, codeName: "空闲" },
  { codeValue: 1, codeName: "配送中" },
  { codeValue: 2, codeName: "维修中" },
]);

const total = ref(0); // 总条数

const filters = reactive<vehicleSchedulingQuery>({
  pageNum: 1,
  pageSize: 10,
});

const tableData = ref<vehicleScheduling[]>();

const handleReset = () => {
  filters.pageNum = 1;
  filters.pageSize = 10;
  filters.licensePlate = undefined;
  filters.driverName = undefined;
  filters.deliveryStatus = undefined;
  handleSearch();
};

function handleSearch() {
  // 这里可以添加搜索逻辑，例如筛选表格数据
  vehicleSchedulingApi.getVehicleMonitoring(filters).then((res: any) => {
    console.log(res);
    tableData.value = res.list;
    total.value = res.total;
  });
  // vehicleSchedulingApi.getVehicleMonitoringCount().then((res: VehicleMonitoringCount) => {
  //   console.log(res, "总数");
  //   deliveryStatusCount.completedCount = res.completedCount;
  //   deliveryStatusCount.deliveringCount = res.deliveringCount;
  //   deliveryStatusCount.pendingCount = res.pendingCount;
  //   deliveryStatusCount.totalCount = res.totalCount;
  // });
}
//各配送状态数量
const deliveryStatusCount = reactive<VehicleMonitoringCount>({
  completedCount: 0,
  deliveringCount: 0,
  pendingCount: 0,
  totalCount: 0,
});

const externalVehicleRules = ref({
  licensePlate: [
    { required: true, message: "请输入车牌号", trigger: "blur" },

    {
      pattern:
        /^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$/,
      message: "请输入正确的车牌号",
      trigger: "blur",
    },
  ],
  driverName: [{ required: true, message: "请输入司机姓名", trigger: "blur" }],
  contactInfo: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
});
const externalVehicleRef = ref();

//新增外部车辆
function handleAddCar() {
  console.log(newVehicle.value, "新增车辆");

  externalVehicleRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }

    vehicleSchedulingApi
      .addExternalVehicle(newVehicle.value)
      .then((res: any) => {
        console.log(res);
        //提示
        ElMessage.success("操作成功");

        handleCarCloseDialog();
        handleSearch();
      })
      .catch((err: any) => {
        console.log(err);
        //提示
        // ElMessage.error(`${err}`);
      });
  });
}

//关闭新增车辆弹窗
function handleCarCloseDialog() {
  externalVehicleDialog.value.visible = false;
  // 清空表单数据
  externalVehicleRef.value?.clearValidate();
  externalVehicleRef.value?.resetFields();
  newVehicle.value.driverName = "";
  newVehicle.value.contactInfo = "";
  newVehicle.value.licensePlate = "";
  newVehicle.value.remark = "";
  newVehicle.value.isExternalVehicle = 0;
}

//查看详情
function handleViewDetail(row: vehicleScheduling & { targetName: string }) {
  selectedRow.value = row;

  selectedRow.value.targetName =
    row?.vehicleInfoDTOList?.filter((ele) => ele.status == 8)[0]?.address || "";
  console.log(selectedRow.value, "车牌号");

  detailDialogVisible.value = true;
}

const handleEdit = (row: vehicleScheduling, type: "edit" | "add") => {
  if (type == "add") {
    externalVehicleDialog.value.title = "新增车辆";
  } else {
    externalVehicleDialog.value.title = "编辑车辆";
  }
  externalVehicleDialog.value.visible = true;
  newVehicle.value = { ...row };
};
const handleDel = (id: number) => {
  ElMessageBox.confirm("确定要删除该车辆吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      vehicleSchedulingApi.deleteVehicle(id).then((res) => {
        console.log(res);
        handleSearch();
        //提示
        ElMessage.success("删除成功");
      });
    })
    .catch(() => {});
};

//车速，锁状态，温度
const vehicleInfo = ref<VehicleMonitoringData & { targetName?: string; currentName?: string }>({
  id: NaN,
  licensePlate: "",
  coordinates: "",
  monitorStatus: "",
  duration: "",
  speed: 0,
  lockStatus: 1,
  temperature: 0,
  currentLocation: "",
  targetName: "",
  currentName: "",
});

const handleGetDriverInfo = (
  driverInfo: VehicleMonitoringData & { targetName?: string; currentName?: string }
) => {
  //地图组件返回的车辆信息
  vehicleInfo.value = driverInfo;
};

onMounted(() => {
  handleSearch();
  getPlateList();
});
</script>
<style scoped></style>
